package org.voovan.korla;

import org.junit.Before;
import org.junit.Test;
import org.voovan.korla.message.Callback;
import org.voovan.korla.message.Msg;
import org.voovan.korla.socket.KorlarConsumer;
import org.voovan.tools.TEnv;
import org.voovan.tools.serialize.TSerialize;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 类文字命名
 *
 * @author: helyho
 * korla Framework.
 * WebSite: https://github.com/helyho/korla
 * Licence: Apache v2 License
 */
public class KorlarConsumerUnit {
    private static boolean sendOnConnect = false;
    private transient KorlarConsumer korlarConsumer;

    static {
        TSerialize.register(TimeMsg.class);
    }

    @Before
    public void before() throws IOException {
        korlarConsumer = new KorlarConsumer("0.0.0.0", 3333, 5000, 5000);
    }

    @Test
    public void testFuture() throws IOException, TimeoutException {
        korlarConsumer.connect();

        int i=0;

        while(i<1000) {
            TimeMsg msg = new TimeMsg();
            msg.setSeq(i);
            korlarConsumer.send(msg);
            System.out.println(msg.getResponse(1000));
            i++;
        }
        int m = 0;
        TEnv.sleep(100);
        System.out.println("Cache size: " +KorlaStatic.MESSAGE.size());
    }

    @Test
    public void testWaitSend() throws IOException, TimeoutException {
        korlarConsumer.connect();

        int i=0;

        while(i<1000) {
            TimeMsg msg = new TimeMsg();
            msg.setSeq(i);
            System.out.println(korlarConsumer.send(msg, 1000));
            i++;
        }

        TEnv.sleep(100);
        System.out.println("Cache size: " +KorlaStatic.MESSAGE.size());
    }

    @Test
    public void testCallBack() throws IOException, TimeoutException {
        korlarConsumer.connect();

        int i=0;

        while(i<1000) {
            //20->16634/s
            if(i%2==0) {
                TEnv.sleep(1);
            }

            TimeMsg msg = new TimeMsg();
            msg.setSeq(i);
            msg.setCallBack(new Callback() {
                @Override
                public Msg apply(Msg t) {
                    System.out.println(t);
                    return null;
                }
            });
            korlarConsumer.send(msg);
            i++;
        }

        TEnv.sleep(100);
        System.out.println("Cache size: " + KorlaStatic.MESSAGE.size());
    }
}
